package com.zzw.mvvm.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseFragment<T extends BaseViewModel> extends Fragment {
    public Unbinder unBinder;
    public T viewModel;
    View mView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(getLayoutId(), container);
        return mView;

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        unBinder = ButterKnife.bind(this, view);
        bindViewModel();
    }

    /**
     * 未与Activity共享的ViewModelProvider
     *
     * @return ViewModelProvider
     */
    public ViewModelProvider getModelProvider() {
        ViewModelProvider.Factory factory = ViewModelProvider.AndroidViewModelFactory.getInstance(this.getActivity().getApplication());
        ViewModelProvider viewModelProvider = new ViewModelProvider(this, factory);
        return viewModelProvider;
        // viewModel = viewModelProvider.get(T);
    }

    /**
     * 与Activity共享的ViewModelProvider
     *
     * @return ViewModelProvider
     */
    public ViewModelProvider getActivityModelProvider() {
        ViewModelProvider.Factory factory = ViewModelProvider.AndroidViewModelFactory.getInstance(this.getActivity().getApplication());
        ViewModelProvider viewModelProvider = new ViewModelProvider(this.getActivity(), factory);
        return viewModelProvider;
        // viewModel = viewModelProvider.get(T);
    }

    /**
     * 直接获取ViewModel
     *
     * @return T
     */
    public T createViewModel(Class<T> c) {
        viewModel = getModelProvider().get(c);
        return viewModel;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (unBinder != null) {
            unBinder.unbind();
        }
    }

    public abstract int getLayoutId();

    public abstract void bindViewModel();

}
